import 'braft-editor/dist/index.css';
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, message, Spin } from 'antd';
import { cloneDeep, difference } from 'lodash';

import { PageHeaderWrapper } from '@ant-design/pro-layout';
import goodsService from '@/services/goods';
import GoodsFormPurchase from '../Goods/goodsFormPurchase.js';
import { router } from 'umi';
import shopAdditionalService from '@/services/shopAdditional';
import busShopService from '@/services/busShop';
import RouterWillLeave from "@/components/RouterWillLeave";

@connect(({ goodsDetail, loading }) => ({
  goodsDetail,
  loading: loading.models.goodsDetail,
}))
class PurchaseDetail extends PureComponent {
  state = {
    id: '',
    buyOutValue: 0,
    loading: false,
    goodsDetail: {},
    categories: [],
    addServiceTableData: [],
    districts: [],
    giveBackList: [],
  };

  componentWillMount() {
    const {
      match: {
        params: { id },
      },
    } = this.props;
    this.findCategories();
    this.getShopAdditionalServiceList();
    this.getGiveBackList();
    this.selectDistrict();
    if (id && id !== 'add') {
      this.getData(id);
    } else {
      this.setState({
        goodsDetail: {
          name: '',
          oldNewDegree: 1,
          labels: [],
          additionals: null,
          shopAdditionals: [],
          buyOutSupport: 0,
          productSkuses: [],
          minRentCycle: '',
          maxRentCycle: '',
          type: 1,
          detail: '',
          province: '',
          city: '',
          freightType: 'PAY',
          addIds: [],
          images: [],
          src: null,
          productId: '',
          salesVolume: null,
          lowestSalePrice: null,
          parameters: [],
          productCouponList: null,
          collected: null,
          specs: [
            { name: '颜色', opeSpecId: 1, values: [] },
            { name: '规格', opeSpecId: 2, values: [] },
          ],
          serviceTel: null,
        },
        id
      });
    }
  }

  getData = (id = this.state.id) => {
    this.setState({
      loading: true,
    });
    goodsService
      .selectProductBuyProductEdit({
        id,
      })
      .then(res => {
        this.setState({
          buyOutValue: 0,
          goodsDetail: res,
          id,
        });
      })
      .finally(() => {
        this.setState({
          loading: false,
        });
      });
  };

  findCategories = () => {
    goodsService.findCategories().then(res => {
      let data = res.httpStatus ? [] : res;
      this.setState({
        categories: data || [],
      });
    });
  };

  getShopAdditionalServiceList = () => {
    shopAdditionalService
      .selectShopAdditionalServicesList({
        pageSize: 9999,
        pageNumber: 1,
        name: '',
      })
      .then(res => {
        // message.success('获取数据成功')
        this.setState({
          addServiceTableData: res.records || [],
        });
      });
  };

  selectDistrict = () => {
    goodsService.selectDistrict().then(res => {
      let data = res.httpStatus ? [] : res;
      this.setState({
        districts: data || [],
      });
    });
  };

  getGiveBackList = () => {
    busShopService.selectShopRuleAndGiveBackByShopId().then(res => {
      let data = res.httpStatus ? [] : res;
      this.setState({
        giveBackList: data || [],
      });
    });
  };

  setInitList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'goodsDetail/selectShopRuleAndGiveBackByShopId',
    });
  };

  changeSpecs = (specs, opeSpecId) => {
    const { goodsDetail } = this.state;
    const _goodsDetail = cloneDeep(goodsDetail);
    _goodsDetail.specs = _goodsDetail.specs.map(f => {
      if (f.opeSpecId === opeSpecId) {
        return specs;
      }
      return f;
    });
    this.setState(
      {
        goodsDetail: _goodsDetail,
      },
      () => {
        this.handleSku();
      },
    );
  };

  handleSku = () => {
    const { goodsDetail } = this.state;
    const _goodsDetail = cloneDeep(goodsDetail);
    let _specs = {},
      colorSpecs = {};
    _goodsDetail.specs.forEach(v => {
      if (v.opeSpecId === 1) {
        colorSpecs = v;
      } else {
        _specs = v;
      }
    });
    const _productSkuses = _goodsDetail.productSkuses;
    const colorSpecsLength = colorSpecs.values.length;
    const specsLength = _specs.values.length;
    let _arr = [];
    for (let i = 0; i < colorSpecsLength; i++) {
      for (let j = 0; j < specsLength; j++) {
        const index_p = _productSkuses.findIndex(_p => {
          return (
            _p.specAll[0].platformSpecValue === colorSpecs.values[i].name &&
            _p.specAll[1].platformSpecValue === _specs.values[j].name
          );
        });
        if (index_p > -1) {
          _arr.push(_productSkuses[index_p]);
        } else {
          _arr.push({
            salePrice: '',
            inventory: '',
            marketPrice: '',
            isHandlingFee: 0,
            specAll: [
              {
                opeSpecId: 1,
                platformSpecName: '颜色',
                platformSpecValue: colorSpecs.values[i].name,
              },
              { opeSpecId: 2, platformSpecName: '规格', platformSpecValue: _specs.values[j].name },
            ],
          });
        }
      }
    }
    _goodsDetail.productSkuses = _arr;
    this.setState({
      goodsDetail: _goodsDetail,
    });
  };

  changeSku = (sku, index) => {
    const { goodsDetail } = this.state;
    const _goodsDetail = cloneDeep(goodsDetail);
    _goodsDetail.productSkuses[index] = sku;
    this.setState({
      goodsDetail: _goodsDetail,
    });
  };

  deleteSku = (index, colorTitle, specTitle) => {
    const { goodsDetail } = this.state;
    const _goodsDetail = cloneDeep(goodsDetail);
    _goodsDetail.productSkuses.splice(index, 1);
    this.setState({
      goodsDetail: _goodsDetail,
    });
  };

  deleteSpecs = (specs, index) => {
    const { goodsDetail } = this.state;
    const _goodsDetail = cloneDeep(goodsDetail);
    _goodsDetail.specs = specs;
    _goodsDetail.productSkuses.splice(index, 1);
    this.setState({
      goodsDetail: _goodsDetail,
    });
  };

  handleSubmit = data => {
    const { goodsDetail, id } = this.state;
    const { categoryIds = [] } = data;

    if (goodsDetail && goodsDetail.isSupportStage === 0) {
      for (let i = 0; i < goodsDetail.productSkuses.length; i++) {
        delete goodsDetail.productSkuses[i].isHandlingFee;
      }
    }
    const isAdd = id && id !== 'add';
   let isAdds = id === 'add' ? "" : id
    const service = isAdd
      ? goodsService.busUpdateDirectBuyProduct
      : goodsService.busInsertDirectBuyProduct;
    service({
      ...goodsDetail,
      ...data,
      specs: goodsDetail.specs,
      categoryId: categoryIds[categoryIds.length - 1],
      id:isAdds,
    }).then(res => {
      const msg = isAdd ? '新增成功' : '更新成功';
      message.success(msg);
      this.cancel();
    });
  };

  onProductBuyout = value => {
    this.setState({
      buyOutValue: value,
    });
  };
  
  cancel = (isPrompt, isSubmit) => {
    this.setState({
      isPrompt,
      isSubmit
    }, () => {
      router.push('/goods/Purchase');
    });
  };
  
  renderRouterWillLeave(){
    const { isPrompt, isSubmit } = this.state
    
    return (
      <RouterWillLeave isPrompt={isPrompt} isSubmit={isSubmit}  />
    )
  }

  render() {
    const {
      loading,
      buyOutValue,
      id,
      goodsDetail,
      categories,
      addServiceTableData,
      districts,
      giveBackList,
    } = this.state;
    console.log(id);
  
    const title = id === 'add' ? '新增商品' : '修改商品';
    return (
      <PageHeaderWrapper title={title}>
        <Spin spinning={loading}>
          <Card>
            {/*{*/}
            {/*  this.renderRouterWillLeave()*/}
            {/*}*/}
            {goodsDetail && (
              <GoodsFormPurchase
                goodsDetail={goodsDetail}
                categories={categories}
                addServiceTableData={addServiceTableData}
                changeSpecs={this.changeSpecs}
                deleteSpecs={this.deleteSpecs}
                changeSku={this.changeSku}
                deleteSku={this.deleteSku}
                districts={districts}
                giveBackList={giveBackList}
                handleSubmit={this.handleSubmit}
                setInitList={this.setInitList}
                editType={id}
                cancel={this.cancel}
                buyOutValue={buyOutValue}
                onProductBuyout={value => this.onProductBuyout(value)}
              />
            )}
          </Card>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default PurchaseDetail;
